package com.ldx.eduline.common.controller;

import com.ldx.eduline.common.bean.FileDTO;
import com.ldx.eduline.common.bean.R;
import com.ldx.eduline.common.utils.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

@RestController
@RequestMapping("upload")
public class OssController {

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    /** 文件上传*/
    @PostMapping
    public R uploadBlog(@RequestParam("file") MultipartFile file) {
        String filename = file.getOriginalFilename();
        System.out.println(filename);
        try {
            // 判断文件
            if (file!=null) {
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    // 上传到OSS
                    FileDTO fileDTO = aliyunOSSUtil.upLoad(newFile);
                    return R.success().addData("fileInfo",fileDTO);
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }
        return R.fail();
    }
}
